package contact.importEmailContact;

import java.io.InputStream;
import java.util.Scanner;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.YahooApi;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;

public class Yahoo {
	private static final String key = "dj0yJmk9cmxjamlGQ1FvTVdvJmQ9WVdrOVZYcE5jRFJrTXpnbWNHbzlOVEEwTmpVMU5qWXkmcz1jb25zdW1lcnNlY3JldCZ4PWUx";
	private static final String secret = "bfa962df82ac632413ad94a4bbe60e18f36806ab";
	// private static String appId="ZNNQAOGUR52PPL4IRY7TLZOOHU";//fengyun
	private static String appId = "DRZC5N3AAOFRU2E24NLNUR3QNE";// fenshen6046
	private static final String AUTHORIZE_URL = "https://api.login.yahoo.com/oauth/v2/request_auth?oauth_token=";
	private static String PROTECTED_RESOURCE_URL = "http://social.yahooapis.com/v1/user/"
			+ appId + "/contacts";

	private static String GUID_URL = "http://social.yahooapis.com/v1/me/guid";

	public static void main(String[] args) throws Exception {
		OAuthService service = new ServiceBuilder().provider(YahooApi.class)
				.apiKey(key).apiSecret(secret)
				// .callback("http://localhost:8080/complex")
				.build();
		Token requestToken = service.getRequestToken();
		System.out.println(AUTHORIZE_URL + requestToken.getToken());
		System.out.print(">>");
		Scanner in = new Scanner(System.in);
		Verifier verifier = new Verifier(in.nextLine());

		// -------------------------------------------
		// get the guid
		Token guidToken = service.getAccessToken(requestToken, verifier);

		OAuthRequest requestGuid = new OAuthRequest(Verb.GET, GUID_URL);
		service.signRequest(guidToken, requestGuid);
		Response responseGuid = requestGuid.send();
		InputStream cont = responseGuid.getStream();
		appId = getGuid(cont);
		System.out.println(appId);
		Token accessToken = service.getAccessToken(requestToken, verifier);
		PROTECTED_RESOURCE_URL = "http://social.yahooapis.com/v1/user/" + appId
				+ "/contacts";
		OAuthRequest request = new OAuthRequest(Verb.GET,
				PROTECTED_RESOURCE_URL);
		service.signRequest(accessToken, request);
		Response response = request.send();

		String body = response.getBody();
		System.out.println(body);

	}

	public static String getGuid(InputStream in) {
		String result = "";
		try {
			SAXReader reader = new SAXReader();
			Document doc = reader.read(in);
			Element root = doc.getRootElement();
			result = root.elementText("value");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
